package tingshu.repository;


import lombok.SneakyThrows;
import tingshu.data_object.UserDO;
import tingshu.util.DBUtil;
import tingshu.util.Log;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class UserRepo {
    @SneakyThrows // lombok，可以让我们不添加 throws 也可以正常抛出受查异常
    public void insert(UserDO userDO) {
        String sql = "insert into users (username, password) values (?,?)";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                ps.setString(1,userDO.username);
                ps.setString(2,userDO.password);

                Log.println("执行 SQL" + ps);
                ps.executeUpdate();
                try (ResultSet rs = ps.getGeneratedKeys()){
                    rs.next();
                    userDO.uid = rs.getInt(1);//获得数据库下的自增uid
                }
            }
        }
    }

    @SneakyThrows
    public UserDO select(String username) {
        String sql = "select uid, username, password from users where username = ?";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setString(1,username);
                Log.println("执行 SQL" + ps);
                ps.executeQuery();
                try (ResultSet rs = ps.getResultSet()) {
                    if (!rs.next()) {
                        //用户名输入错误,没有找到用户
                        return null;
                    }

                    return new UserDO(rs.getInt(1),
                            rs.getString("username"),
                            rs.getString("password"));
                }
            }
        }
    }
}
